#include "precompile.h"

#include "ServiceManager.h"

ServiceManager::ServiceManager()
{
}

ServiceManager::~ServiceManager()
{
}

void ServiceManager::RegisterServiceProvider(const String& service,vclsid clsidServiceProvider)
{
	ServiceProviderRegistration::const_iterator itfindInregistration = m_registrations.find(service);
	if (itfindInregistration == m_registrations.end())
		m_registrations.insert(std::make_pair(service,clsidServiceProvider));
}

void ServiceManager::ReplaceServiceProvider(const String& service,vclsid clsidServiceProvider)
{
	ASSERT(clsidServiceProvider != CLASSID_NULL);
	if (clsidServiceProvider == CLASSID_NULL)
		return;

	ServiceProviderRegistration::iterator itfindInregistration = m_registrations.find(service);
	if (itfindInregistration != m_registrations.end())
	{
		itfindInregistration->second = clsidServiceProvider;
	}
}

IObject* ServiceManager::GetServiceProvider(const String& service) const
{
	ServiceProviderCache::const_iterator itfindIncache = m_serviceProviderCache.find(service);
	if (itfindIncache != m_serviceProviderCache.end())
		return itfindIncache->second.P();

	ServiceProviderRegistration::const_iterator itfindInregistration = m_registrations.find(service);
	if (itfindInregistration != m_registrations.end())
	{
		vclsid clsidSericeProvider = itfindInregistration->second;
		sys::ObjectPtr objServiceProvider;
		vresult vr = objServiceProvider.CreateObject(clsidSericeProvider);
		if (ISFAILED(vr))
		{
			ASSERT(FALSE);
			return NULL;
		}
		IObject* pServiceProviderObj = objServiceProvider.P();
		m_serviceProviderCache.insert(std::make_pair(service,objServiceProvider));
		return pServiceProviderObj;
	}
	return NULL;
}